package top.xcxdl.rural.controller.admin;


import com.alibaba.fastjson.JSONObject;
import top.xcxdl.rural.common.Res;
import top.xcxdl.rural.config.initexception.ErrorEnum;
import top.xcxdl.rural.entity.BackAuthRule;
import top.xcxdl.rural.service.IBackAuthGroupService;
import top.xcxdl.rural.service.IBackAuthRuleService;
import top.xcxdl.rural.utils.JWTUtils;
import top.xcxdl.rural.utils.JwtInterceptor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Ding
 * @since 2022-01-27
 */
@Api("后台权限控制器")
@RestController
@RequestMapping("/admin/adminRule")
public class BackAuthRuleController {

    @Resource
    private IBackAuthGroupService groupService;
    @Resource
    private IBackAuthRuleService service;

    private static final String SUPER_ADMIN = "SUPER_ADMIN";

    /**
     * 添加 or 编辑菜单
     *
     * @param bean BackAuthRule实体
     * @return res
     */
    @ApiOperation("添加 or 编辑菜单")
    @ResponseBody
    @PostMapping("/doEdit")
    public Res<JSONObject> doEdit(@RequestBody BackAuthRule bean) {
        int editNum = 0;
        boolean isAdd = bean.getRuleId() == null;
        editNum += service.doEdit(bean);
        if (editNum > 0) {
            return Res.success(isAdd ? "添加成功" : "编辑成功");
        } else {
            return Res.error();
        }
    }

    /**
     * 删除菜单
     *
     * @param data {ids: 菜单id字符串（逗号分开）-需转为int数组}
     * @return res
     */
    @ApiOperation("删除菜单")
    @ResponseBody
    @PostMapping("/doDelete")
    public Res<JSONObject> doDelete(@RequestBody JSONObject data) {
        //处理前端数据
        String[] idsStr = String.valueOf(data.get("ids")).split(",");
        List<Integer> ids = new ArrayList<>();
        for (String s : idsStr) {
            ids.add(Integer.parseInt(s));
        }
        //遍历，确认不含有特殊菜单，否则return
        int beforeIdsSize = ids.size();
        for (int i = 0; i < ids.size(); i++) {
            System.err.println(ids.get(i));
            if (1 == service.getById(ids.get(i)).getDisabled()) {
                ids.remove(i--);
            }
        }
        if (ids.size() < beforeIdsSize) {
            return Res.error("选择中含有" + (beforeIdsSize - ids.size()) + "个特殊菜单（不可删除），请取消相应的勾选");
        }
        //初始化
        int delNum = 0;
        //执行删除
        delNum += service.doDeleteBy(ids);
        if (delNum >= ids.size()) {
            return Res.success("已删除" + delNum + "个嵌套（含）菜单");
        } else if (delNum > 0) {
            return Res.success("部分删除成功：" + delNum + "/" + (ids.size()));
        } else {
            return Res.error();
        }
    }
}
